import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
import { getRouterReq } from '@/api/routers'
import Main from '@/components/main'
const { homeName } = config

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'

const INITIAL_ROUTERS_LEN = 5 // 默认路由数量

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

const updateRoutes = (router, menuList) => {
  if (menuList.length > 0) {
    for (var i = 0; i < menuList.length; i++) {
      router.options.routes.push(menuList[i])
    }
    router.addRoutes(menuList)
  }
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  console.log(token, 'token------------------')
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
    // next()
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      console.log(store.state.user.hasGetInfo, 'store.state.user.hasGetInfo===')
      console.log(router.options.routes.length, 'router.options.routes.length===')
      if (router.options.routes.length <= INITIAL_ROUTERS_LEN) {
        let menuList = store.state.user.menus
        updateRoutes(router, menuList)
      }
      next()
    } else {
      store.dispatch('getUserInfo').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
        let menuList = user.menus
        updateRoutes(router, menuList)
        if (to.name == null) {
          next(to)
        } else {
          next()
        }
      }).catch((err) => {
        console.log('登录过期')
        setToken('')
        next({
          name: 'login'
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
